<?php

namespace App\Services\Stats\User;

use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Admin\Stats\Retention\Day\Game;
use App\Models\Admin\Stats\Retention\Day\Sign;

class RetentionService extends Service
{
    use DatabaseMysql;

    /**
     * 制作统计字段
     *
     * @return string
     */
    protected function statsFields()
    {
        $columns[] = 'timed';
        $columns[] = 'SUM(drr_1_num) as drr_1_num';
        $columns[] = 'SUM(drr_2_num) as drr_2_num';
        $columns[] = 'SUM(drr_3_num) as drr_3_num';
        $columns[] = 'SUM(drr_7_num) as drr_7_num';
        $columns[] = 'SUM(drr_15_num) as drr_15_num';
        $columns[] = 'SUM(drr_30_num) as drr_30_num';

        return implode(',', $columns);
    }

    /**
     * 数据列表【游戏留存】
     */
    public function game($request)
    {
        $query = Game::dbTable();

        // 筛选【平台】
        $this->makeWhereParam($request, 'plat_code', $query);
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $query, 'timed');

        // 数据条数
        $total = (clone $query)->distinct('timed')->count();
        // 排序分页
        $this->makeOrderParam($request, $query, 'timed')->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->selectRaw($this->statsFields())
            ->groupBy('timed')
            ->get();

        return [
            $collection,
            $total
        ];
    }

    /**
     * 数据列表【注册留存】
     */
    public function sign($request)
    {
        $query = Sign::dbTable();

        // 筛选【平台】
        $this->makeWhereParam($request, 'plat_code', $query);
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $query, 'timed');

        // 数据条数
        $total = (clone $query)->distinct('timed')->count();
        // 排序分页
        $this->makeOrderParam($request, $query, 'timed')->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->selectRaw($this->statsFields())
            ->groupBy('timed')
            ->get();

        return [
            $collection,
            $total
        ];
    }
}
